const { pool } = require('../config/db');

// 自定义映射表用于加密
const customMap = { 
  '0': 'K', '1': 'L', '2': 'M', '3': 'N', 
  '4': 'P', '5': 'Q', '6': 'R', '7': 'S', 
  '8': 'T', '9': 'U', 'A': 'V', 'B': 'W', 
  'C': 'X', 'D': 'Y', 'E': 'Z', 'F': 'H', 
  'G': 'J', 'H': 'A', 'I': 'B', 'J': 'C', 
  'K': 'D', 'L': 'E', 'M': 'F', 'N': 'G', 
  'O': 'I', 'P': 'O', 'Q': '1', 'R': '2', 
  'S': '3', 'T': '4', 'U': '5', 'V': '6' 
};

/**
 * 将ID转换为32进制并使用自定义映射表加密
 * @param {number} id - 要加密的ID
 * @returns {string} - 加密后的字符串
 */
const encryptId = (id) => {
  // 将ID转换为32进制
  const base32 = id.toString(32).toUpperCase();
  
  // 使用自定义映射表加密
  let encrypted = '';
  for (let i = 0; i < base32.length; i++) {
    const char = base32[i];
    encrypted += customMap[char] || char;
  }
  
  return encrypted;
};

exports.getAllResources = async (req, res) => {
    const [rows] = await pool.query('SELECT * FROM resources');
    return res.json(rows);
};

exports.getResourceById = async (req, res) => {
    const { id } = req.params;
    const [[resource]] = await pool.query('SELECT * FROM resources WHERE id = ?', [id]);
    if (!resource) {
        return res.status(404).send('Resource not found');
    }
    return res.json(resource);
};

exports.searchResources = async (req, res) => {
    const { name, generated_link } = req.query;
    let query = 'SELECT * FROM resources WHERE 1=1';
    const params = [];
    
    if (name) {
        query += ' AND name LIKE ?';
        params.push(`%${name}%`);
    }
    
    if (generated_link) {
        query += ' AND generated_link = ?';
        params.push(generated_link);
    }
    
    const [rows] = await pool.query(query, params);
    return res.json(rows);
};

exports.createResource = async (req, res) => {
    try {
        const { name } = req.body;
        
        if (!name) {
            return res.status(400).send('Resource name is required');
        }
        
        // 先插入资源，只提供name字段
        const [result] = await pool.query(
            'INSERT INTO resources (name) VALUES (?)', 
            [name]
        );
        
        const newId = result.insertId;
        
        // 使用ID生成加密的链接
        const generated_link = encryptId(newId);
        
        // 更新资源，添加生成的链接
        await pool.query(
            'UPDATE resources SET generated_link = ? WHERE id = ?',
            [generated_link, newId]
        );
        
        return res.status(201).json({
            message: 'Resource created successfully',
            id: newId,
            name,
            generated_link
        });
    } catch (error) {
        console.error('Error creating resource:', error);
        return res.status(500).send('Failed to create resource');
    }
};

exports.updateResource = async (req, res) => {
    try {
        const { id } = req.params;
        const updates = req.body;
        
        // 验证是否有要更新的字段
        if (Object.keys(updates).length === 0) {
            return res.status(400).send('No fields to update');
        }
        
        // 检查资源是否存在
        const [[existingResource]] = await pool.query('SELECT * FROM resources WHERE id = ?', [id]);
        if (!existingResource) {
            return res.status(404).send('Resource not found');
        }
        
        // 如果要更新generated_link，检查是否与其他资源冲突
        // if (updates.generated_link && updates.generated_link !== existingResource.generated_link) {
        //     const [[conflictResource]] = await pool.query(
        //         'SELECT id FROM resources WHERE generated_link = ? AND id != ?', 
        //         [updates.generated_link, id]
        //     );
            
        //     if (conflictResource) {
        //         return res.status(409).send('A resource with this generated link already exists');
        //     }
        // }
        
        // 构建动态更新查询
        const fields = [];
        const values = [];
        
        if (updates.name !== undefined) {
            fields.push('name = ?');
            values.push(updates.name);
        }
        
        // if (updates.generated_link !== undefined) {
        //     fields.push('generated_link = ?');
        //     values.push(updates.generated_link);
        // }
        
        if (fields.length === 0) {
            return res.status(400).send('No valid fields to update');
        }
        
        // 添加ID到参数数组
        values.push(id);
        
        // 执行更新
        await pool.query(
            `UPDATE resources SET ${fields.join(', ')} WHERE id = ?`, 
            values
        );
        
        // 获取更新后的数据
        const [[updatedResource]] = await pool.query('SELECT * FROM resources WHERE id = ?', [id]);
        
        return res.json({
            message: 'Resource updated successfully',
            resource: updatedResource
        });
    } catch (error) {
        console.error('Error updating resource:', error);
        return res.status(500).send('Failed to update resource');
    }
};

exports.deleteResource = async (req, res) => {
    try {
        const { id } = req.params;
        
        // 检查资源是否存在
        const [[existingResource]] = await pool.query('SELECT * FROM resources WHERE id = ?', [id]);
        if (!existingResource) {
            return res.status(404).send('Resource not found');
        }
        
        // 检查是否有依赖关系（例如，是否有targets引用此resource_id）
        const [relatedTargets] = await pool.query('SELECT COUNT(*) as count FROM redirect_targets WHERE resource_id = ?', [id]);
        if (relatedTargets[0].count > 0) {
            return res.status(400).send('Cannot delete resource: it is being used by one or more targets');
        }
        
        // 执行删除
        await pool.query('DELETE FROM resources WHERE id = ?', [id]);
        
        return res.json({
            message: 'Resource deleted successfully',
            id: parseInt(id)
        });
    } catch (error) {
        console.error('Error deleting resource:', error);
        return res.status(500).send('Failed to delete resource');
    }
};

exports.deleteResourceAndAllTargets = async (req, res) => {
    try {
        const { id } = req.params;

        // 检查资源是否存在
        const [[existingResource]] = await pool.query('SELECT * FROM resources WHERE id = ?', [id]);
        if (!existingResource) {
            return res.status(404).send('Resource not found');
        }

        // 检查是否有依赖关系（例如，是否有targets引用此resource_id）
        const [relatedTargets] = await pool.query('SELECT COUNT(*) as count FROM redirect_targets WHERE resource_id = ?', [id]);
        if (relatedTargets[0].count > 0) {
            await pool.query('DELETE FROM redirect_targets WHERE resource_id = ?', [id]);
        }

        // 执行删除
        await pool.query('DELETE FROM resources WHERE id = ?', [id]);

        return res.json({
            message: 'Resource deleted successfully',
            id: parseInt(id)
        });
    } catch (error) {
        console.error('Error deleting resource:', error);
        return res.status(500).send('Failed to delete resource');
    }
};